using System;
using System.Security.Cryptography;

namespace Wantn.Share.DataCry
{
	public sealed class AES
	{
		public static bool GenKey(out byte[] rgbKey, out byte[] rgbIV)
		{
			bool flag = false;
			Rijndael rijndael = null;
			try
			{
				rijndael = Rijndael.Create();
				rijndael.Mode = CipherMode.CBC;
				rijndael.Padding = PaddingMode.PKCS7;
				rijndael.GenerateKey();
				rijndael.GenerateIV();
				rgbKey = rijndael.Key;
				rgbIV = rijndael.IV;
				return true;
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				rijndael?.Clear();
			}
		}

		public static byte[] Encrypt(byte[] data, byte[] rgbKey, byte[] rgbIV)
		{
			byte[] array = null;
			Rijndael rijndael = null;
			ICryptoTransform cryptoTransform = null;
			try
			{
				rijndael = Rijndael.Create();
				rijndael.Mode = CipherMode.CBC;
				rijndael.Padding = PaddingMode.PKCS7;
				cryptoTransform = rijndael.CreateEncryptor(rgbKey, rgbIV);
				return cryptoTransform.TransformFinalBlock(data, 0, data.Length);
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				cryptoTransform?.Dispose();
				rijndael?.Clear();
			}
		}

		public static byte[] Encrypt(byte[] data, out byte[] rgbKey, out byte[] rgbIV)
		{
			byte[] array = null;
			Rijndael rijndael = null;
			ICryptoTransform cryptoTransform = null;
			try
			{
				rijndael = Rijndael.Create();
				rijndael.Mode = CipherMode.CBC;
				rijndael.Padding = PaddingMode.PKCS7;
				rijndael.GenerateKey();
				rijndael.GenerateIV();
				rgbKey = rijndael.Key;
				rgbIV = rijndael.IV;
				cryptoTransform = rijndael.CreateEncryptor(rgbKey, rgbIV);
				return cryptoTransform.TransformFinalBlock(data, 0, data.Length);
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				cryptoTransform?.Dispose();
				rijndael?.Clear();
			}
		}

		public static byte[] Decrypt(byte[] data, byte[] rgbKey, byte[] rgbIV)
		{
			byte[] array = null;
			Rijndael rijndael = null;
			ICryptoTransform cryptoTransform = null;
			try
			{
				rijndael = Rijndael.Create();
				rijndael.Mode = CipherMode.CBC;
				rijndael.Padding = PaddingMode.PKCS7;
				cryptoTransform = rijndael.CreateDecryptor(rgbKey, rgbIV);
				return cryptoTransform.TransformFinalBlock(data, 0, data.Length);
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				cryptoTransform?.Dispose();
				rijndael?.Clear();
			}
		}

	}
}
